package blog.dao;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import blog.domain.Article;
import blog.domain.User;

@Transactional(propagation=Propagation.MANDATORY)
public class ArticleDAO 
{
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Transactional(propagation=Propagation.SUPPORTS)
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public void addArticle(Article article)
	{
		Session session = sessionFactory.getCurrentSession();
		session.persist(article);
	}
	
	public Article getArticle(int id)
	{
		Session session = sessionFactory.getCurrentSession();
		Article article = (Article)session.get(Article.class, id);
		return article;
	}
	
	public void updateArticle(Article article)
	{
		Session session = sessionFactory.getCurrentSession();
		session.update(article);
	}
	
	public void deleteArticle(Article article)
	{
		Session session = sessionFactory.getCurrentSession();
		//session.delete(article.getComments());
		session.delete(article);
	}
	
	@SuppressWarnings("unchecked")
	public List<Article> getArticles()
	{
		Session session = sessionFactory.getCurrentSession();
		return session.createQuery("from Article").list();
	}

	public void editable(User user) {
		for(Article article:user.getArticles()) {
			article.setEditable(true);
			sessionFactory.getCurrentSession().update(article);
		}
	}

	public void unEditable(int id) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from User u where u.id = :id");
		query.setParameter("id", id);
		User user = (User)query.uniqueResult();
		for(Article article:user.getArticles()) {
			article.setEditable(false);
			session.update(article);
		}
	}

	@SuppressWarnings("unchecked")
	public void initEditable() {
		Session session = sessionFactory.getCurrentSession();
		List<Article> articles = session.createQuery("from Article").list();
		for(Article article:articles) {
			article.setEditable(false);
			session.update(article);
		}
	}
	
}
